package com.txw.e.edittext;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PersistableBundle;
import android.os.RemoteException;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.e.weixin.test.IRemoteService;
import com.e.weixin.test.IRemoteServiceCallback;

public class MainActivity extends AppCompatActivity {
    IRemoteService  remoteService;
    Button sum;
    EditText edt_a,edt_b;
    void initRemoteService(){
        edt_a = (EditText) findViewById(R.id.edt_a);
        edt_b = (EditText) findViewById(R.id.edt_b);
        sum = (Button) findViewById(R.id.btn_sum);
        sum.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    int a = Integer.valueOf(edt_a.getText() + "");
                    int b = Integer.valueOf(edt_b.getText() + "");
                    remoteService.add(a, b);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        Intent i = new Intent("com.e.weixin.test.RemoteService");
        bindService(i, mConnection, Context.BIND_AUTO_CREATE);
    }
    private ServiceConnection mConnection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            remoteService = IRemoteService.Stub.asInterface(service);
            try {
                remoteService.registerCallback(remoteServiceCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            // As part of the sample, tell the user what happened.
            Toast.makeText(MainActivity.this, "remote service connected",
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // As part of the sample, tell the user what happened.
            Toast.makeText(MainActivity.this, "remote service disconnected",
                    Toast.LENGTH_SHORT).show();
        }
    };
    IRemoteServiceCallback.Stub remoteServiceCallback  = new IRemoteServiceCallback.Stub(){

        @Override
        public void valueChanged(int value) throws RemoteException {
            Toast.makeText(MainActivity.this, "RemoteCallBack valueChanged", Toast.LENGTH_SHORT).show();
            sum.setText("" + value);
        }
    };


    EditText search;

    EditText customStyle;
    AutoCompleteTextView autoComplete;
    EditText imageEdit;
    Button drawableBtn,dynamicDrawableBtn;

    TextView text;
    ActionBar   actionBar;


    /**
     * 超链接
     */
    private void addUrlSpan() {
        SpannableString spanString = new SpannableString("超链接");
        URLSpan span = new URLSpan("tel:0123456789");
        spanString.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.append(spanString);
    }


    /**
     * 文字背景颜色
     */
    private void addBackColorSpan() {
        SpannableString spanString = new SpannableString("颜色2");
        BackgroundColorSpan span = new BackgroundColorSpan(Color.YELLOW);
        spanString.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.append(spanString);
    }


    /**
     * 文字颜色
     */
    private void addForeColorSpan() {
        SpannableString spanString = new SpannableString("颜色1");
        ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);
        spanString.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.append(spanString);
    }


    /**
     * 字体大小
     */
    private void addFontSpan() {
        SpannableString spanString = new SpannableString("36号字体");
        AbsoluteSizeSpan span = new AbsoluteSizeSpan(36);
        spanString.setSpan(span, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.append(spanString);
    }


    /**
     * 粗体，斜体
     */
    private void addStyleSpan() {
        SpannableString spanString = new SpannableString("BIBI");
        StyleSpan span = new StyleSpan(Typeface.BOLD_ITALIC);
        spanString.setSpan(span, 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.append(spanString);
    }


    /**
     * 删除线
     */
    private void addStrikeSpan() {
        SpannableString spanString = new SpannableString("删除线");
        StrikethroughSpan span = new StrikethroughSpan();
        spanString.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.append(spanString);
    }

    /**
     * 下划线
     */
    private void addUnderLineSpan() {
        SpannableString spanString = new SpannableString("下划线");
        UnderlineSpan span = new UnderlineSpan();
        spanString.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.append(spanString);
    }

    /**
     * 图片
     */
    private void addImageSpan() {

        SpannableString spanString = new SpannableString(" ");//最终SpannableString中的" "替换成一个图片
        Drawable d = getResources().getDrawable(R.drawable.indicator_input_error);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        spanString.setSpan(span, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        text.append(spanString);
    }


    void initSearch(){
        search = (EditText) findViewById(R.id.search);

        search.setOnEditorActionListener(new EditText.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    Snackbar snackbar = Snackbar.make(v, "虽然是search，但是是actionSend", Snackbar.LENGTH_SHORT);
                    snackbar.show();
                    return true;
                }
                return false;
            }
        });

        //处理右侧图片事件
        search.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (event.getRawX() >= (search.getRight() - search.getCompoundDrawables()[2].getBounds().width())) {
                        // your action here
                        search.getText().clear();
                        Snackbar snackbar = Snackbar.make(v, "数据已经清空", Snackbar.LENGTH_SHORT);
                        snackbar.show();
                        return true;
                    }
                }
                return false;
            }
        });
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                System.out.println("beforeTextChanged :" + s);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                System.out.println("onTextChanged :" + s);
                actionBar.setTitle(s);

            }

            @Override
            public void afterTextChanged(Editable s) {
                System.out.println("afterTextChanged :" + s);
            }
        });

        findViewById(R.id.btn_clickable).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final SpannableString ss = new SpannableString("http://www.g.cn");
                ClickableSpan click = new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        Snackbar snackbar = Snackbar.make(search, ss + " clicked", Snackbar.LENGTH_SHORT);
                        snackbar.show();
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                    }
                };
                ss.setSpan(click, 0, ss.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                //下面代码是给TextView添加一个ClickableSpan

                text.setMovementMethod(LinkMovementMethod.getInstance());//如果使用这个span的view不设置这个参数，没有点击事件
                text.setHighlightColor(Color.TRANSPARENT); //设置点击后的颜色为透明，不然的高亮背景色
                text.setText(ss);

                //下面代码是给EditText添加一个ClickableSpan
//                Editable et = search.getText();
//                System.out.println(et);
//                search.setMovementMethod(LinkMovementMethod.getInstance());
//                et.insert(search.getSelectionStart(), ss);
//                System.out.println(et);
            }
        });

    }
    void initTextView(){
        text = (TextView) findViewById(R.id.tv);
        addBackColorSpan();
        addFontSpan();
        addForeColorSpan();
        addImageSpan();
        addStrikeSpan();
        addStyleSpan();
        addUnderLineSpan();
        addUrlSpan();

    }

    void initAutoCompleteView(){
        autoComplete = (AutoCompleteTextView) findViewById(R.id.edt_autocomplete);
        // Get the string array
        String[] countries = getResources().getStringArray(R.array.countries_array);
        // Create the adapter and set it to the AutoCompleteTextView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
        autoComplete.setAdapter(adapter);
        autoComplete.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                actionBar.setTitle(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    void insertImage(){

        imageEdit = (EditText) findViewById(R.id.edt_insert_img);

        drawableBtn = (Button) findViewById(R.id.btn_insert_drawable_span);

        dynamicDrawableBtn = (Button) findViewById(R.id.btn_insert_dynamic_drawable_span);

        imageEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                actionBar.setTitle(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        drawableBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {

                //insertImg是个EditText,假设当前已经输入abc
                //打印插入图片之前的文本，这里输出： abc
                System.out.println(imageEdit.getText());

                //构造一个内容只有一个图片的 SpannableString
                SpannableString imgSpannable = new SpannableString(" ");
                //得到图片
                Drawable drawable = getResources().getDrawable(R.drawable.indicator_input_error);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

                //构造ImageSpan
                ImageSpan span = new ImageSpan(drawable);
                //注意要两边都不包括,就是只把“ ”换成图片
                imgSpannable.setSpan(span, 0,1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                //获取EditText中的内容
                Editable et = imageEdit.getText();
                //把新构造的只有一个图片的SpannableString插入到EditText中
                int start = imageEdit.getSelectionStart();
                et.insert(start, imgSpannable);

                //打印插入图片之后的文本,这里会输出： ab c
                System.out.println(imageEdit.getText());
                //其中ab与c之间的空白就是插入的图片。
                //其它view可以直接使用这个文本并能正确显示“ab图片c”，不用我们解析，把其中的空格替换成图片。
            }
        });

        dynamicDrawableBtn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {

        //构造一个内容只有一个图片的 SpannableString
        SpannableString dynamic = new SpannableString(" ");

        //构造DynamicDrawableSpan,注意其中的参数 ALIGN_BASELINE让插入的图片最底部基于文本的基线对齐；
        //ALIGN_BOTTOM 基于EditText的底部对齐。。
        DynamicDrawableSpan dynamicDrawableSpan = new DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BASELINE) {
            @Override
            public Drawable getDrawable() {
                Drawable d = getResources().getDrawable(R.drawable.indicator_input_error);
                d.setBounds(0, 0, 36, 36);
                return d;
            }
        };
        //注意要两边都不包括,就是只把“ ”换成图片
        dynamic.setSpan(dynamicDrawableSpan, 0,1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        //获取EditText中的内容
        Editable et = imageEdit.getText();
        //把新构造的只有一个图片的SpannableString插入到EditText中
        int start = imageEdit.getSelectionStart();
        et.insert(start, dynamic);

            }
        });
    }
    void initCustomStyle(){
        customStyle = (EditText) findViewById(R.id.edt_custom_style);
        customStyle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                actionBar.setTitle(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
    public void showSoftKeyboard(View view) {//指定想要输入键盘的view
        if (view.requestFocus()) {//1，取得焦点
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);//2，用InputMethodManager显示键盘
        }
    }


    //lifecycle

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        System.out.println("onCreate");

        setContentView(R.layout.activity_main);

        actionBar = getSupportActionBar();

        initTextView();

        initSearch();

        initAutoCompleteView();

        initCustomStyle();

        insertImage();

        initRemoteService();//通过aidl调用远程的一个service,求a+b

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        System.out.println("onRestart");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        System.out.println("onRestoreInstanceState");
    }

    @Override
    protected void onResume() {
        super.onResume();
        System.out.println("onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        System.out.println("onPause");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        System.out.println("onSaveInstanceState");
    }

    @Override
    protected void onStop() {
        super.onStop();
        System.out.println("onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.out.println("onDestroy");
    }
}
